<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right" class="page-breadcrumb">
            <el-breadcrumb-item>资源管理</el-breadcrumb-item>
            <el-breadcrumb-item>权限列表</el-breadcrumb-item>
        </el-breadcrumb>
        <div>
            <div
                style="float:left;width:200px;border:1px solid #EBEEF5;overflow:auto;height:calc(100vh - 96px);"
                class="left-tree-content"
                v-loading="loadingApplist"
            >
                <el-tree
                    ref="appTree"
                    style="margin-top:0;"
                    node-key="code"
                    id="appTree"
                    :current-node-key="queryForm.appCode"
                    highlight-current
                    :data="appTree"
                    @node-click="handleNodeClick"
                    :render-content="renderContent"
                ></el-tree>
            </div>
            <div
                style="float:left;width:calc(100% - 202px);height:calc(100vh - 97px);overflow:auto;"
            >
                <table-ex
                    ref="tableEx"
                    :treeProps="{}"
                    :queryCallback="queryCallback"
                    :expandRowKeys="[...expandRowKeys]"
                    :row-class-name="tableRowClassName"
                    :onExpandChange="onExpandChange"
                >
                    <el-table-column label="名称" show-overflow-tooltip min-width="200">
                        <template slot-scope="scope">
                            <strong>{{scope.row.name}}</strong>
                            <el-tag
                                style="margin-left:10px;"
                                effect="plain"
                                size="small"
                                type="danger"
                                v-if="scope.row.state === 2"
                            >禁用</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="code" label="编码"></el-table-column>
                    <el-table-column label="HTTP请求" show-overflow-tooltip>
                        <template slot-scope="scope">
                            <template v-if="scope.row.url">
                                <span
                                    v-for="(item, index) in scope.row.url.split(';')"
                                    :key="index"
                                >
                                    {{item}}
                                </span>
                            </template>
                        </template>
                    </el-table-column>
                    <el-table-column prop="type" label="权限类型">
                        <template slot-scope="scope">
                            <el-tag
                                effect="plain"
                                size="small"
                                type="success"
                                v-if="scope.row.type === 1"
                            >系统</el-tag>
                            <el-tag
                                effect="plain"
                                size="small"
                                type="warning"
                                v-else-if="scope.row.type === 2"
                            >菜单</el-tag>
                            <el-tag effect="plain" size="small" v-else-if="scope.row.type === 3">元素</el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column prop="authentication" label="认证">
                        <template slot-scope="scope">
                            <i
                                v-if="scope.row.authentication===1"
                                style="color:#67C23A;"
                                class="el-icon-success"
                            ></i>
                            <i
                                v-if="scope.row.authentication===2"
                                style="color:red;"
                                class="el-icon-error"
                            ></i>
                        </template>
                    </el-table-column>
                    <el-table-column prop="authorization" label="权限">
                        <template slot-scope="scope">
                            <i
                                v-if="scope.row.authorization===1"
                                style="color:#67C23A;"
                                class="el-icon-success"
                            ></i>
                            <i
                                v-if="scope.row.authorization===2"
                                style="color:red;"
                                class="el-icon-error"
                            ></i>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="200">
                        <template slot-scope="scope">
                            <el-button
                                v-if="authMap['xzbjqx']"
                                type="default"
                                size="mini"
                                class="button-in-cell"
                                @click="onAdd(scope.row)"
                            >添加</el-button>
                            <el-button
                                v-if="authMap['xzbjqx']"
                                type="default"
                                size="mini"
                                class="button-in-cell"
                                @click="onUpdate(scope.row)"
                            >编辑</el-button>
                            <el-dropdown size="small" style="margin-left:10px;">
                                <span class="el-dropdown-link">
                                    <el-button type="default" size="mini" class="button-in-cell">
                                        更多
                                        <i class="el-icon-arrow-down el-icon--right"></i>
                                    </el-button>
                                </span>
                                <el-dropdown-menu slot="dropdown">
                                    <el-dropdown-item
                                        v-if="scope.row.state !== 1 && authMap['qyjyqx']"
                                        style="color:#67C23A"
                                        icon="iconfont icon-check-circle"
                                        @click.native="onEnableResource(scope.row)"
                                    >启用</el-dropdown-item>
                                    <el-dropdown-item
                                        v-if="scope.row.state === 1 && authMap['qyjyqx']"
                                        style="color:#E6A23C"
                                        icon="el-icon-remove-outline"
                                        @click.native="onDisableResource(scope.row)"
                                    >禁用</el-dropdown-item>
                                    <el-dropdown-item
                                        v-if="scope.row.type !== 1 && authMap['scqx']"
                                        style="color:#ed4014"
                                        icon="el-icon-delete"
                                        @click.native="onDelete(scope.row.id)"
                                    >删除</el-dropdown-item>
                                </el-dropdown-menu>
                            </el-dropdown>
                        </template>
                    </el-table-column>
                </table-ex>
            </div>
        </div>

        <sys-resource-add
            :mdl="mdl"
            :show="showAddDialog"
            :success="onAddSuccess"
            :cancel="onAddCancel"
        ></sys-resource-add>
        <sys-resource-update
            :mdl="mdl"
            :app="updateApp"
            :show="showUpdateDialog"
            :success="onUpdateSuccess"
            :cancel="onUpdateCancel"
            :id="updateId"
        ></sys-resource-update>
    </div>
</template>

<script>
import sys_resource_api from '../../api/sys_resource_api'
import sys_application_api from '../../api/sys_application_api'
import SysResourceAdd from './SysResourceAdd.vue'
import SysResourceUpdate from './SysResourceUpdate.vue'
import TableEx from '../../components/TableEx.vue'
import { mapState } from 'vuex'

export default {
    components: {
        SysResourceAdd,
        SysResourceUpdate,
        TableEx,
    },
    data() {
        return {
            queryForm: {
                id: '',
                key: '',
                createTime: '',
                createTimeRange: '',
                appCode: null
            },
            showAddDialog: false,
            showUpdateDialog: false,
            updateId: null,
            mdl: null,
            treeData: [],
            updateApp: false,
            appList: [],
            loadingApplist: false,
            appTree: [],
            currentPid: null,
            expandRowKeys: null,
        }
    },
    created() {
        this.loadingApplist = true
        sys_application_api.appList().then(data => {
            this.loadingApplist = false
            this.appList = data
            this.appTree = this.appList.map(e => {
                return {
                    label: e.name,
                    key: e.code
                }
            })
        }).catch(err => {
            this.loadingApplist = false
            this.$message.error(err.message)
        })
    },
    computed: {
        ...mapState({
            authMap: state => state.auth.authMap,
            userInfo: state => state.auth.userInfo
        })
    },
    methods: {
        queryCallback() {
            if (!this.queryForm.appCode) {
                return null
            }
            return sys_resource_api.appTreeData(this.queryForm.appCode).then(data => {
                this.treeData = [data]
                return Promise.resolve([data])
            })
        },
        onQuery(code) {
            if (code) {
                this.queryForm.appCode = code
            }
            this.$refs.tableEx.refresh()
        },
        deepTreeForItem(tree, id) {
            let l = []
            let lst = this.treeToList(tree)
            while (id) {
                const w = lst.find(e => e.id == id)
                if (w) {
                    l.unshift(w)
                    id = w.parentId
                } else {
                    break
                }
            }
            return l
        },
        treeToList(tree) {
            let l = []
            tree.forEach(e => {
                if (e.children && e.children.length > 0) {
                    l = l.concat(this.treeToList(e.children))
                }
                l.push(e)
            })
            return l
        },
        onAdd(row) {
            this.currentPid = row.id
            this.mdl = {
                pid: row.id,
                pname: row.name,
                appList: this.deepTreeForItem(this.treeData, row.id)
            }
            this.showAddDialog = true
        },
        onAddSuccess(data) {
            this.showAddDialog = false
            this.onQuery()
            // this.$refs.tableEx.append(data, this.currentPid)
        },
        onAddCancel() {
            this.showAddDialog = false
        },
        onUpdate(row) {
            this.mdl = {
                pid: row.id,
                pname: row.name,
                appList: this.deepTreeForItem(this.treeData, row.id)
            }
            this.updateApp = row.type === 1
            this.updateId = row.id
            this.showUpdateDialog = true
        },
        onUpdateSuccess() {
            this.showUpdateDialog = false
            this.onQuery()
        },
        onUpdateCancel() {
            this.showUpdateDialog = false
        },
        onDelete(id) {
            this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: true,
            }).then(() => {
                sys_resource_api.delete(id).then(data => {
                    this.$message.success('删除成功!')
                    this.onQuery()
                }).catch(err => {
                    this.$message.error(err.message)
                })
            }).catch(err => {
            })
        },
        tableRowClassName({ row, rowIndex }) {
            // if (row.type === 2) {
            //     return 'warning-row'
            // } else if (row.type === 1) {
            //     return 'success-row'
            // }
            return ''
        },
        onDisableResource(res) {
            this.$confirm(`<p>禁用权限：<strong>${res.name}</strong></p><p>是否继续?</p>`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: true,
            }).then(() => {
                sys_resource_api.disableResource(res.id).then(data => {
                    this.$message.success('禁用成功')
                    this.onQuery()
                }).catch(err => {
                    this.$message.error(err.message)
                })
            }).catch(err => {
            })
        },
        onEnableResource(res) {
            this.$confirm(`<p>启用权限：<strong>${res.name}</strong></p><p>是否继续?</p>`, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: true,
            }).then(() => {
                sys_resource_api.enableResource(res.id).then(data => {
                    this.$message.success('启用成功')
                    this.onQuery()
                }).catch(err => {
                    this.$message.error(err.message)
                })
            }).catch(err => {
            })
        },
        handleNodeClick(data) {
            this.queryForm.appCode = data.key
            this.expandRowKeys = this.getTreeCache('treeTableCache_' + this.queryForm.appCode + "_" + this.userInfo.id)
            this.onQuery()
        },
        renderContent(h, { node, data, store }) {
            return (
                <span class="el-tree-node__label" style="padding:10px 0 10px 0;">
                    <div>
                        <span>{node.label}</span>
                    </div>
                    <div>
                        <el-tag effect="plain" type="info" size="mini" style="margin-top:5px;">{data.key}</el-tag>
                    </div>
                </span>)
        },
        getTreeCache(name) {
            let cache = localStorage.getItem(name) ? localStorage.getItem(name).split(',') : []
            let m = cache.map(item => item.toString())
            return m
        },
        onExpandChange(row, expanded) {
            this.setTreeCache('treeTableCache_' + this.queryForm.appCode + "_" + this.userInfo.id, row.id, expanded)
        },
        setTreeCache(name, key, expanded) {
            var val = key.toString(),
                cache = localStorage.getItem(name) ? localStorage.getItem(name).split(',') : [],
                index = cache.findIndex(item => item === val)
            if (expanded === undefined) {
                return index == -1 ? false : val
            }
            if (expanded && index == -1) {
                cache.push(val)
            }
            if (!expanded && index > -1) {
                cache.splice(index, 1)
            }
            localStorage.setItem(name, cache.join(','));
        },
    }
}
</script>

<style>
.el-table .warning-row {
    background: oldlace;
}

.el-table .success-row {
    background: #f0f9eb;
}
#appTree .el-tree-node__content {
    border-bottom: 1px solid rgb(235, 238, 245);
}
</style>

